"""
MySQL数据库执行公共函数
"""
import os
import re
import time

from yat.test import Node
from yat.test import macro

from .Constant import Constant
from .Logger import Logger


class CommonMySQL:
    def __init__(self, node_name='mysql5'):
        # root用户还是数据库安装的用户执行脚本。数据库用户默认dbuser（见conf/nodes.yml）
        self.log = Logger()
        self.Constant = Constant()
        self.node = Node(node=node_name)

    def console(self, msg):
        """
        打印关键日志
        :param msg: 需要打印的信息
        """
        self.log.info("---- {} ----".format(msg))

    def execut_db_sql(self, sql, dbname=None, host=None,
                      port=None, user=None, password=None, other_para=''):
        """
        使用gsql的方式调用数据库sql语句
        :param sql: sql语句
        :param host: 数据库主机
        :param password: 数据库用户密码
        :param user: 数据库用户名
        :param dbname: 数据库名
        :param port: 数据库端口
        :param other_para:
        :return: sql语句执行结果
        """
        db_name = dbname if dbname else self.node.db_name
        db_port = port if port else self.node.db_port
        db_user = user if user else self.node.db_user
        db_pwd = password if password else self.node.db_password
        db_host = host if host else self.node.db_host
        if self.node.name == 'mysql8':
            shell = f'cd {macro.MYSQL8_BINPATH};' \
                    f'./mysql -D {db_name} -P {db_port}  ' \
                    f'-u {db_user} -p{db_pwd} -h {db_host} {other_para} ' \
                    f'-e "{sql}" '
        else:
            shell = f'cd {macro.MYSQL5_BINPATH};' \
                    f'./mysql -D {db_name} -P {db_port}  ' \
                    f'-u {db_user} -p{db_pwd} -h {db_host} {other_para} ' \
                    f'-e "{sql}" '
        self.log.info(shell)
        msg = self.node.sh(shell).result()
        return msg